package service

//数据连接初始化
import (
	"errors"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/spf13/viper"
	"log"
	"xorm.io/core"
)

var DbEngine *xorm.Engine

func init() {
	//读取yaml配置文件
	viper.SetConfigName("application")
	//设置配置文件目录的搜索目录
	viper.AddConfigPath("./config/")

	//读取
	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			log.Println("no such config file")
		} else {
			log.Println("read config error")
		}
		log.Fatal(err) //读取配置文件的致命错误
	}
	userName := viper.GetString(`mysql.username`)
	password := viper.GetString(`mysql.password`)
	host := viper.GetString(`mysql.host`)
	port := viper.GetString(`mysql.port`)
	database := viper.GetString(`mysql.database`)
	driverName := viper.GetString(`mysql.driver`)
	DsName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", userName, password, host, port, database)
	err := errors.New("")
	DbEngine, err = xorm.NewEngine(driverName, DsName)
	if err != nil && err.Error() != "" {
		panic(err.Error())
	}
	//是否显示sql语句
	DbEngine.ShowSQL(false)
	//设置数据库最大打开的连接数

	DbEngine.SetMaxOpenConns(2000)
	tbMapper := core.NewPrefixMapper(core.SnakeMapper{}, "sys_")
	DbEngine.SetTableMapper(tbMapper)
	//自动建表 待定
	//err1 :=DbEngine.Sync2(new(entity.User))
	/*if err1 != nil {
		fmt.Println("adas")
	}*/
	fmt.Println("init database ok")
}
